import React from 'react';
import { Carousel, Icon } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import styles from './index.less';

const getTotalDaysNum = m => {
    const start = m.startOf('month').weekday();
    const end = m.endOf('month').weekday();
    const year = m.get('year');
    const month = m.get('month');
    const days = new Date(year, month + 1, 0).getDate();
    return days + start + 6 - end;
};

const getMonthDateList = m => {
    const month = m.format('YYYY-MM');
    const days = getTotalDaysNum(m);
    const result = [...Array(days).keys()].reduce((acc, val) => {
        const now = m
            .clone()
            .startOf('month')
            .weekday(0)
            .add(val, 'days');
        acc.push({
            date: now.format('YYYY-MM-DD'),
            label: now.format('D'),
            isMonth: now.format('YYYY-MM') === month,
            isWeekend: [5, 6].includes(now.weekday())
        });
        return acc;
    }, []);
    return result;
};

const getMonthData = (value, index) => getMonthDateList(moment(value).add(index, 'months'));

const getWeekDateList = m => {
    const month = m.format('YYYY-MM');
    const result = [...Array(7).keys()].reduce((acc, val) => {
        const now = m
            .clone()
            .weekday(0)
            .add(val, 'days');
        acc.push({
            date: now.format('YYYY-MM-DD'),
            label: now.format('D'),
            isMonth: now.format('YYYY-MM') === month,
            isWeekend: [5, 6].includes(now.weekday())
        });
        return acc;
    }, []);
    return result;
};

const getWeekData = (value, index) => getWeekDateList(moment(value).add(index, 'weeks'));

// http://localhost:8000/external/interview/changeInterview?id=cabcadccc705b27b96e5322e668627ca

const CalendarSelect = ({ value, defaultExpanded, defaultSelectedList = [], onChange, onExpandChange }) => {
    const carouselRef = React.useRef();
    const slideRef = React.useRef(null);
    const [sliders, setSliders] = React.useState([-1, 0, 1]);
    const [curIndex, setCurIndex] = React.useState(1);
    const [expanded, setExpanded] = React.useState(defaultExpanded);

    const handleAfterChange = (index, unit) => {
        let sliderTemp = [-1, 0, 1];
        if (index === 0) {
            sliderTemp = [0, 1, -1];
        } else if (index === 2) {
            sliderTemp = [1, -1, 0];
        }
        setSliders(sliderTemp);
        setCurIndex(index);
        if (onChange) {
            if (slideRef.current) {
                onChange(slideRef.current);
                slideRef.current = null;
            } else {
                onChange(
                    moment(value)
                        .add(sliders[index], unit)
                        .format('YYYY-MM-DD')
                );
            }
        }
    };

    React.useEffect(() => {
        setExpanded(expanded);
    }, [expanded]);

    const renderItem = (item, isMonth) => (
        <div
            key={item.date}
            className={cn(styles.dateItem, {
                [styles.current]: item.date === value,
                [styles.isSelected]: defaultSelectedList.includes(item.date)
            })}
            onClick={() => {
                if (onChange) {
                    if (isMonth) {
                        if (!item.isMonth) {
                            slideRef.current = item.date;
                            if (moment(item.date).isAfter(moment(value))) {
                                carouselRef.current.next();
                            } else {
                                carouselRef.current.prev();
                            }
                        } else {
                            onChange(item.date);
                        }
                    } else {
                        onChange(item.date);
                    }
                }
            }}
        >
            <span className={item.isWeekend || !item.isMonth ? styles.weekend : ''}>{item.label}</span>
        </div>
    );

    return (
        <div className={styles.calendarWrap}>
            <div className={styles.dateContainer}>
                {[0, 1, 2, 3, 4, 5, 6].map(item => (
                    <div className={styles.dateItem} key={item}>
                        <span style={{ fontSize: 12, color: '#858b9b' }}>
                            {moment()
                                .weekday(item)
                                .format('dddd')
                                .replace('星期', '')}
                        </span>
                    </div>
                ))}
            </div>
            <div style={{ width: '100%' }}>
                {expanded && (
                    <Carousel
                        ref={carouselRef}
                        afterChange={i => handleAfterChange(i, 'months')}
                        dots={false}
                        slide="section"
                        initialSlide={curIndex}
                    >
                        {sliders.map(it => (
                            <section key={it}>
                                <div className={styles.mainWrap}>
                                    <div className={cn(styles.dateContainer, styles.mainBox)}>
                                        {getMonthData(value, it)?.map(item => renderItem(item, true))}
                                    </div>
                                </div>
                            </section>
                        ))}
                    </Carousel>
                )}
                {!expanded && (
                    <Carousel
                        afterChange={i => handleAfterChange(i, 'weeks')}
                        dots={false}
                        slide="section"
                        initialSlide={curIndex}
                    >
                        {sliders.map(it => (
                            <section key={it}>
                                <div className={cn(styles.mainWrap, styles.weekWrap)}>
                                    <div className={cn(styles.dateContainer, styles.mainBox)}>
                                        {getWeekData(value, it)?.map(item => renderItem(item))}
                                    </div>
                                </div>
                            </section>
                        ))}
                    </Carousel>
                )}
            </div>
            <div
                style={{ padding: '6px 12px' }}
                onClick={() => {
                    setExpanded(!expanded);
                    if (onExpandChange) {
                        onExpandChange();
                    }
                }}
            >
                <Icon type={expanded ? 'up' : 'down'} style={{ color: '#DCE0E8' }} />
            </div>
            <div className={styles.dividerLine}></div>
        </div>
    );
};

export default CalendarSelect;
